<template>
  <div class="category">
    <!-- 左侧边主分类 -->
    <div class="sidebar">
      <van-sidebar v-model="activeKey">
        <van-sidebar-item
          v-for="category in categories"
          :key="category.id"
          :title="category.name"
          :to="{name: 'sub', params: {id: category.id}}"
        />
      </van-sidebar>
    </div>
    <!-- :to="{path: '/category/sub-category', query: {}}" -->
    <!-- 右侧子分类 -->
    <div class="sub-category">
      <keep-alive>
        <router-view />
      </keep-alive>
    </div>
  </div>
</template>

<script>
import { getAllCategories } from '../../api/category'
export default {
  name: 'Category',
  data() {
    return {
      activeKey: 0,
      categories: [],
    }
  },
  beforeRouteUpdate(to, from, next) {
    next(to.path !== '/category')
  },
  activated() {
    // 当分类组件激活时，判断
    if (this.categories.length) {
      let { id } = this.$route.params
      if (id) {
        id = Number(id)
        this.activeKey = this.categories.findIndex(cate => cate.id === id)
        return
      }
      // 如果已有分类数据，则说明已经缓存
      // 组件了，默认向选中的子分类页面跳转
      this.$router.push({
        name: 'sub',
        params: {
          id: this.categories[this.activeKey].id,
        },
      })
    } else {
      // 没有分类数据，则查询所有主分类
      getAllCategories()
        .then(data => {
          this.categories = data.list.slice(1)
        })
        .then(() => {
          // 如果地址中有子分类跳转路径，
          // 则向对应路径跳转，否则向第
          // 一个子分类跳转
          let { id } = this.$route.params
          if (id) {
            id = Number(id)
            this.activeKey = this.categories.findIndex(cate => cate.id === id)
          }
          this.$router.push({
            name: 'sub',
            params: {
              id: this.categories[this.activeKey].id,
            },
          })
        })
    }
  },
  // deactivated() {
  //   console.log('category deactivated...')
  // },
}
</script>

<style lang="less">
  .category {
    display: flex;

    .sub-category {
      padding: 12px 0;
      flex: 1;
    }
  }
</style>
